package com.ruoyi.canteen.controller.v1;


import com.alibaba.fastjson.JSONObject;
import com.ruoyi.canteen.service.FeiePrintService;
import com.ruoyi.canteen.service.ICanteenCpOrderService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.AESUtil;
import com.ruoyi.common.utils.http.HttpUtils;
//import com.ruoyi.framework.web.domain.server.Sys;
//import com.ruoyi.weika.domain.jiju.JiJuConfigResult;
//import com.ruoyi.weixin.domain.UserInfoResponse;
//import com.ruoyi.weixin.domain.daikou.DaikouResponse;
//import com.ruoyi.weixin.domain.daikou.DaikouResponseData;
import com.ruoyi.weika.domain.CanteenJijuConfig;

import com.ruoyi.weika.service.ICanteenJijuConfigService;
import com.ruoyi.weixin.domain.UserInfoResponse;
import com.ruoyi.weixin.domain.daikou.DaikouResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

import static com.ruoyi.common.utils.AESUtil.Encrypt;

@RestController
@RequestMapping("/v1/pay")
public class WeikaPayController extends BaseController {

    @Autowired
    ICanteenCpOrderService canteenCpOrderService;

    @Autowired
    ICanteenJijuConfigService canteenJijuConfigService;

    @Autowired
    private FeiePrintService feiePrintService;

    private static final Logger log = LoggerFactory.getLogger(WeikaPayController.class);

    @PostMapping("/weikaPay")
    public AjaxResult pay(@RequestParam("order_id") String order_id,@RequestParam("amount") int amount,@RequestParam("token") String token ,@RequestParam("mdId") String mdId ) {
    //public AjaxResult pay() {
        log.info("入参:"+order_id+"-"+amount+"-"+token+"-"+mdId+"-");
        UserInfoResponse user = getUserInfo(token);
        if(user != null)
            log.info("获取用户信息成功");
        else
            log.info("获取用户信息失败");
        CanteenJijuConfig config = canteenJijuConfigService.selectCanteenJijuConfigByMdId(Long.parseLong(mdId) );
        //CanteenJijuConfig config = new CanteenJijuConfig();
        if(config !=null)
        {
            log.info("获取配置信息成功");
            DaikouResponse rs = new DaikouResponse();
            long timestamp = System.currentTimeMillis()/1000;
            // 需要加密的字串
            String cSrc = AESUtil.getStringRandom(10)+":"+timestamp+":1";
            try {

                String enString =  Encrypt(cSrc, config.getKey(), config.getKey().substring(0,16));
                Map<String,Object> map = new HashMap<>();
                map.put("order_id",order_id);
                map.put("amount",amount);
                // System.out.println("auth_code:"+user.getAuth_code());

                if(user !=null)
                    map.put("auth_code",user.getAuth_code());
                else
                    return AjaxResult.error("获取用户信息失败,请从微卡入口进入");

                map.put("md5",config.getMd5());
                map.put("order_time",System.currentTimeMillis()/1000);
                map.put("offline",0);
                map.put("scene","authcode");
                Map<String,String> headerMap = new HashMap<>();
                headerMap.put("Content-type", "application/json;charset=UTF-8");
                headerMap.put("authorization","WxToken "+config.getJijuNo()+":"+enString);
                //log.info("authorization:"+"WxToken "+config.getJijuNo()+":"+enString);
                String form = HttpUtils.https("https://payapi.weixiao.qq.com/pappay",map,headerMap,enString);
                System.out.println(form);
                log.info("交易返回信息:"+form);
                JSONObject userJson = JSONObject.parseObject(form);
                rs = JSONObject.toJavaObject(userJson, DaikouResponse.class);
                if(rs != null && rs.getCode()==0)
                {
                    String userCode = rs.getData().getUser_id();
                    int result = canteenCpOrderService.confirmPayByUserCodeAndNo(userCode, order_id);
                    if(result > 0){
                        // 增加付款成功后，直接打印 add by zw@21211202
                        if(feiePrintService.printOrder(order_id)){
                            // 正常打印
                        }else{
                            // 异常打印，日志输出及推送提醒
                        }
                    }else {
                        log.error("工号:"+userCode+";订单ID:"+order_id + ";支付成功，但更新订单状态失败!");
                    }
                    log.info("回写订单:"+order_id+";更新订单状态result:" + String.valueOf(result));
                }
                return AjaxResult.success(rs);

            } catch (Exception e) {
                e.printStackTrace();
                log.error("订单ID:"+order_id + ";微卡支付异常!"+e.toString());
                return AjaxResult.error("error",e.getMessage());
            }
        }else
        {
            log.info("获取配置信息失败");
            return AjaxResult.error("error","获取配置信息失败!");
        }


        /*
        String cKey = "5D14D863E5F82D8013A73AC768B8C53C";
        // app_secret 取前16位;
        String cIv = "5D14D863E5F82D80";
        long timestamp = System.currentTimeMillis()/1000;

        // 需要加密的字串
        String cSrc = AESUtil.getStringRandom(10)+":"+timestamp+":1";
        DaikouResponse rs = new DaikouResponse();
        try {
            String enString =  Encrypt(cSrc, cKey, cIv);
            Map<String,Object> map = new HashMap<>();
            map.put("order_id",order_id);
            map.put("amount",amount);
           // System.out.println("auth_code:"+user.getAuth_code());
            log.info(order_id+"-"+amount+"");
            //map.put("auth_code","http://wx.url.cn/v003.1632449703.JquFT3.Swl_c5pjnPJmAb-xtcZoAA-3Zoek44SjcP46SiLFgbi0YVsz8BEmQbvTYqMBp3nl_XbEsNRQjhn8G3jLak4CUz4lNfA3gwTDFXYP5hrT5s-hPVx9GlOjalJ67FM1dOUATaLUozO1kDq1UC5ZalfdH5fnQWPlI75BK4XFAsijdSY");
            //map.put("auth_code","http://wx.url.cn/v003.1630329192.yZwmNu.V_sqi_h9auikE_maAJwuy9WGZsyWvA5i0X0I_jBAFeluM551AyqJwpUKR5-274V13UkMHRWt9dUwizrZ9ITJsv-qaAksliVQcAFz84u1CQjNJ4h3ubLN8VC2XcLVn9_gCGa5PUn2VEEI8Q4p8rZcXdSrZhq-hPt24QNbYB8cgRE");
            if(user !=null)
                map.put("auth_code",user.getAuth_code());
            else
                return AjaxResult.error("获取用户信息失败,请从微卡入口进入");


            map.put("md5","82dfe449d5dedff6b7ddc71aa3d4c100");
            map.put("order_time",System.currentTimeMillis()/1000);
            map.put("offline",0);
            map.put("scene","authcode");
            Map<String,String> headerMap = new HashMap<>();
            headerMap.put("Content-type", "application/json;charset=UTF-8");
            headerMap.put("authorization","WxToken WXVM202109220002:"+enString);
            log.info("authorization:"+"WxToken WXVM202109220002:"+enString);
            String form = HttpUtils.https("https://payapi.weixiao.qq.com/pappay",map,headerMap,enString);
            System.out.println(form);
            JSONObject userJson = JSONObject.parseObject(form);
            rs = JSONObject.toJavaObject(userJson, DaikouResponse.class);
            if(rs != null && rs.getCode()==0)
            {
               canteenCpOrderService.confirmPayByUserCodeAndNo(rs.getData().getUser_id(),order_id);
            }
            return AjaxResult.success(rs);

        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("error",e.getMessage());
        }
        * */


    }

    @PostMapping("/weikaPayTest")
    public AjaxResult payTest(@RequestParam("order_id") String order_id,@RequestParam("amount") int amount,@RequestParam("token") String token ,@RequestParam("mdId") String mdId ) {
        //public AjaxResult pay() {

        //UserInfoResponse user = getUserInfo(token);
        String cKey = "5D14D863E5F82D8013A73AC768B8C53C";
        // app_secret 取前16位;
        String cIv = "5D14D863E5F82D80";
        long timestamp = System.currentTimeMillis()/1000;

        // 需要加密的字串
        String cSrc = AESUtil.getStringRandom(10)+":"+timestamp+":1";
        //DaikouResponse rs = new DaikouResponse();
        try {
            String enString =  Encrypt(cSrc, cKey, cIv);
            Map<String,Object> map = new HashMap<>();
            map.put("order_id",order_id);
            map.put("amount",amount);
            // System.out.println("auth_code:"+user.getAuth_code());
            log.info(order_id+"-"+amount+"");
            //map.put("auth_code","http://wx.url.cn/v003.1632449703.JquFT3.Swl_c5pjnPJmAb-xtcZoAA-3Zoek44SjcP46SiLFgbi0YVsz8BEmQbvTYqMBp3nl_XbEsNRQjhn8G3jLak4CUz4lNfA3gwTDFXYP5hrT5s-hPVx9GlOjalJ67FM1dOUATaLUozO1kDq1UC5ZalfdH5fnQWPlI75BK4XFAsijdSY");
            map.put("auth_code","http://wx.url.cn/v003.1630329192.yZwmNu.V_sqi_h9auikE_maAJwuy9WGZsyWvA5i0X0I_jBAFeluM551AyqJwpUKR5-274V13UkMHRWt9dUwizrZ9ITJsv-qaAksliVQcAFz84u1CQjNJ4h3ubLN8VC2XcLVn9_gCGa5PUn2VEEI8Q4p8rZcXdSrZhq-hPt24QNbYB8cgRE");

            map.put("md5","82dfe449d5dedff6b7ddc71aa3d4c100");
            map.put("order_time",System.currentTimeMillis()/1000);
            map.put("offline",1);
            map.put("scene","authcode");
            Map<String,String> headerMap = new HashMap<>();
            headerMap.put("Content-type", "application/json;charset=UTF-8");
            headerMap.put("authorization","WxToken WXVM202109220002:"+enString);
            log.info("authorization:"+"WxToken WXVM202109220002:"+enString);
            String form = HttpUtils.https("https://payapi.weixiao.qq.com/pappay",map,headerMap,enString);
            System.out.println(form);
            JSONObject userJson = JSONObject.parseObject(form);
            DaikouResponse rs = JSONObject.toJavaObject(userJson, DaikouResponse.class);
            return AjaxResult.success(rs);

        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("error",e.getMessage());
        }

    }



    @PostMapping("/weikaPay1")
    public UserInfoResponse  getUserInfo(@RequestParam("token") String token)
    {
        //String url = "https://tygate.weixiao.qq.com/connect/oauth/get-user-detail";
        String url = "https://open.wecard.qq.com/connect/oauth/get-user-detail";

        Map<String,Object> map = new HashMap<>();
        map.put("access_token",token);

        Map<String,String> headerMap = new HashMap<>();
        headerMap.put("Content-type", "application/json;charset=UTF-8");

        String rtn = null;
        UserInfoResponse cp = new UserInfoResponse();
        try {
            rtn = HttpUtils.https(url,map,headerMap,null);

            JSONObject userJson = JSONObject.parseObject(rtn);
            cp = JSONObject.toJavaObject(userJson, UserInfoResponse.class);
            System.out.println(cp.getAuth_code());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cp;
    }

//    private static final Logger log = LoggerFactory.getLogger(WeikaPayController.class);
//    @PostMapping("/weikaPay")
//    public AjaxResult pay(@RequestParam("order_id") String order_id,@RequestParam("amount") int amount,@RequestParam("token") String token ) {
//    //public AjaxResult pay() {
//
//        UserInfoResponse user = getUserInfo(token);
//        String cKey = "5D14D863E5F82D8013A73AC768B8C53C";
//        // app_secret 取前16位;
//        String cIv = "5D14D863E5F82D80";
//        long timestamp = System.currentTimeMillis()/1000;
//
//        // 需要加密的字串
//        String cSrc = AESUtil.getStringRandom(10)+":"+timestamp+":1";
//        //DaikouResponse rs = new DaikouResponse();
//        try {
//            String enString =  Encrypt(cSrc, cKey, cIv);
//            Map<String,Object> map = new HashMap<>();
//            map.put("order_id",order_id);
//            map.put("amount",amount);
//           // System.out.println("auth_code:"+user.getAuth_code());
//            log.info(order_id+"-"+amount+"");
//            //map.put("auth_code","http://wx.url.cn/v003.1632449703.JquFT3.Swl_c5pjnPJmAb-xtcZoAA-3Zoek44SjcP46SiLFgbi0YVsz8BEmQbvTYqMBp3nl_XbEsNRQjhn8G3jLak4CUz4lNfA3gwTDFXYP5hrT5s-hPVx9GlOjalJ67FM1dOUATaLUozO1kDq1UC5ZalfdH5fnQWPlI75BK4XFAsijdSY");
//            //map.put("auth_code","http://wx.url.cn/v003.1630329192.yZwmNu.V_sqi_h9auikE_maAJwuy9WGZsyWvA5i0X0I_jBAFeluM551AyqJwpUKR5-274V13UkMHRWt9dUwizrZ9ITJsv-qaAksliVQcAFz84u1CQjNJ4h3ubLN8VC2XcLVn9_gCGa5PUn2VEEI8Q4p8rZcXdSrZhq-hPt24QNbYB8cgRE");
//            map.put("auth_code",user.getAuth_code());
//            map.put("md5","82dfe449d5dedff6b7ddc71aa3d4c100");
//            map.put("order_time",System.currentTimeMillis()/1000);
//            map.put("offline",1);
//            map.put("scene","authcode");
//            Map<String,String> headerMap = new HashMap<>();
//            headerMap.put("Content-type", "application/json;charset=UTF-8");
//            headerMap.put("authorization","WxToken WXVM202109220002:"+enString);
//            log.info("authorization:"+"WxToken WXVM202109220002:"+enString);
//            String form = HttpUtils.https("https://payapi.weixiao.qq.com/pappay",map,headerMap,enString);
//            System.out.println(form);
//            JSONObject userJson = JSONObject.parseObject(form);
//            DaikouResponse rs = JSONObject.toJavaObject(userJson, DaikouResponse.class);
//            return AjaxResult.success(rs);
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            return AjaxResult.error("error",e.getMessage());
//        }
//
//    }
//
//    @PostMapping("/weikaPay1")
//    public UserInfoResponse  getUserInfo(@RequestParam("token") String token)
//    {
//        //String url = "https://tygate.weixiao.qq.com/connect/oauth/get-user-detail";
//        String url = "https://open.wecard.qq.com/connect/oauth/get-user-detail";
//
//        Map<String,Object> map = new HashMap<>();
//        map.put("access_token",token);
//
//        Map<String,String> headerMap = new HashMap<>();
//        headerMap.put("Content-type", "application/json;charset=UTF-8");
//
//        String rtn = null;
//        UserInfoResponse cp = new UserInfoResponse();
//        try {
//            rtn = HttpUtils.https(url,map,headerMap,null);
//
//            JSONObject userJson = JSONObject.parseObject(rtn);
//            cp = JSONObject.toJavaObject(userJson, UserInfoResponse.class);
//            System.out.println(cp.getAuth_code());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return cp;
//    }

    @PostMapping("/weikaRefund")
    public AjaxResult refund(@RequestParam("order_id") String order_id,@RequestParam("mdId") String mdId)
    {
        log.info("退款入参:"+order_id+"门店id:+"+mdId);

        CanteenJijuConfig config = canteenJijuConfigService.selectCanteenJijuConfigByMdId(Long.parseLong(mdId) );
        if(config !=null)
        {
            log.info("获取配置信息成功");
            long timestamp = System.currentTimeMillis()/1000;
            String cSrc = AESUtil.getStringRandom(10)+":"+timestamp+":1";
            try {

                String enString =  Encrypt(cSrc, config.getKey(), config.getKey().substring(0,16));
                Map<String,Object> map = new HashMap<>();
                map.put("refund_id",order_id+"_refund");
                map.put("order_id",order_id);

                Map<String,String> headerMap = new HashMap<>();
                headerMap.put("Content-type", "application/json;charset=UTF-8");
                headerMap.put("authorization","WxToken "+config.getJijuNo()+":"+enString);
                //log.info("authorization:"+"WxToken "+config.getJijuNo()+":"+enString);
                String rs = HttpUtils.https("https://payapi.weixiao.qq.com/refund",map,headerMap,enString);
                if(rs != null)
                    return AjaxResult.success(rs);
                else
                    return AjaxResult.error("调用退款接口失败！");

            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.error("error",e.getMessage());
            }
        }else
        {
            log.info("获取配置信息失败");
            return AjaxResult.error("error","获取配置信息失败!");
        }
    }
}
